package org.misalen.web.restful.util;

import java.util.Map;

import org.json.JSONObject;

public class TypedInput {

	public static String imei = "";
	public static String macCode = "Android";
	public static String deviceInfo = "MIUI";
	public static String osVersion = "4.2.2";
	public static Integer version = 1;
	public static String uid = "";

	public static JSONObject buildJson(JSONObject data) {
		if (data == null) {
			data = new JSONObject();
		}
		JSONObject dataObj = new JSONObject();
		JSONUtil.putObj(dataObj, "filter", buildFilter());
		JSONUtil.putObj(dataObj, "data", data);
		System.err.println(dataObj.toString());
		return dataObj;
	}

	public static JSONObject buildMap(Map<String, Object> data) {
		JSONObject dataJson = new JSONObject();
		for (String key : data.keySet()) {
			JSONUtil.putObj(dataJson, key, data.get(key));
		}
		JSONObject dataObj = new JSONObject();
		JSONUtil.putObj(dataObj, "filter", buildFilter());
		JSONUtil.putObj(dataObj, "data", dataJson);
		return dataObj;
	}

	public static JSONObject buildFilter() {

		Long macTime = System.currentTimeMillis();

		String correctKey = TextUtil.MD5(imei + macCode) + TextUtil.MD5(String.valueOf(uid) + String.valueOf(macTime));

		String nonceStr = TextUtil.getNonceNum(10);

		String sign = TextUtil.MD5(correctKey + nonceStr);

		JSONObject filter = new JSONObject();
		JSONUtil.putObj(filter, "imei", imei);
		JSONUtil.putObj(filter, "macCode", macCode);
		JSONUtil.putObj(filter, "osVersion", osVersion);
		JSONUtil.putObj(filter, "deviceInfo", deviceInfo);
		JSONUtil.putObj(filter, "version", version);
		JSONUtil.putObj(filter, "uid", uid);
		JSONUtil.putObj(filter, "macTime", macTime);
		JSONUtil.putObj(filter, "nonceStr", nonceStr);
		JSONUtil.putObj(filter, "sign", sign);

		return filter;
	}
}
